package service.mail;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.text.Normalizer;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MailerImplGmailSmtp implements Mailer {
    private static Logger logger = Logger.getLogger(MailerImplGmailSmtp.class.getName());

    private final String SMTP_HOST_NAME = "smtp.gmail.com";
    private final String SMTP_AUTH_USER = "neco@gmail.com";
    private final String SMTP_AUTH_PWD = "heslo";
    private final int SMTP_HOST_PORT = 465;

    public MailerImplGmailSmtp() {
    }

    public static void main(String args[]) throws Exception {
        final String emailMsgTxt = "kukukuk u";
        final String emailSubjectTxt = "kukuku ukuk ukuku";
        final String emailFromAddress = "topservis.test@gmail.com";
        final String[] emailList = {"topservis.test@gmail.com"};
        new MailerImplGmailSmtp().postMail(emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
    }
    /* </TEST> */

    public void postMail(String recipients[], String subject,
                         String message, String from) throws MessagingException {
        boolean debug = true;

        if (debug) {
            for (String string : recipients) {
                logger.info("recipients:" + string);
            }
            logger.info("subject:" + subject);
            logger.info("message:" + message);
            logger.info("from:" + from);
        }
        message = Normalizer.normalize(message, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "");

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtps");
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.port", SMTP_HOST_PORT);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtps.quitwait", "false"); //required to get rid of a strange SSL exception :

        Session mailSession = Session.getDefaultInstance(props);
        mailSession.setDebug(debug);
        Transport transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");

        // set the from and to address
        msg.setFrom(new InternetAddress(from));

        InternetAddress[] addressTo = new InternetAddress[recipients.length];


        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);


        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);


        // Setting the Subject and Content Type
        Thread transportThread = new TransportThread(transport, msg);
        transportThread.start();
    }

    private class TransportThread extends Thread {

        private Transport transport;
        private MimeMessage msg;

        public TransportThread(Transport transport, MimeMessage msg) {
            this.transport = transport;
            this.msg = msg;
        }

        @Override
        public void run() {
            try {
                transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);
                transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
                transport.close();
            } catch (MessagingException ex) {
                Logger.getLogger(MailerImplGmailSmtp.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
